<template>
	<view class="second-rectangle">
		<view class="hourly-forecast">
			<view class="hour" v-for="(item, index) in forecast.slice(0, 5)" :key="index">
				<text class="time">{{ formatHour(item.fxTime) }}</text>
				<view class="temp-container">
					<image class="weather-icon iconfont" :class="`qi-${item.icon}`" alt="weather icon" />
					<text class="temp">{{ item.temp }}</text>
				</view>
			</view>
		</view>
		<!-- 分割线 -->
		<view class="divider"></view>
		<view class="hourly-forecast">
			<view class="hour" v-for="(item, index) in forecast.slice(5)" :key="index">
				<text class="time">{{ formatHour(item.fxTime) }}</text>
				<view class="temp-container">
					<image class="weather-icon iconfont" :class="`qi-${item.icon}`" alt="weather icon" />
					<text class="temp">{{ item.temp }}°</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	
	import {
		host,
		key
	} from '@/common/weather_api';
	import {
		ref,
		defineProps,
		onBeforeMount
	} from 'vue';

	
	const forecast = ref([]);
	const {
		location
	} = defineProps({
		location: String
	});

	const formatHour = (timeString) => {
		let dt = new Date(timeString);
		let hour = dt.getHours();
		let period = hour < 12 || hour === 24 ? 'AM' : 'PM';
		let formattedHour = hour % 12;
		if (hour === 12) formattedHour = 12;
		return `${formattedHour} ${period}`;
	};

	const api_url = `https://${host}/v7/weather/24h?location=${location}&key=${key}`;
	const getHourlyForecast = () => {
		uni.request({
			url: api_url,
			method: 'GET',
			success: (res) => {
				forecast.value = res.data.hourly.slice(0, 10);
			}
		})
	}

	onBeforeMount(() => {
		getHourlyForecast();
	})
</script>

<style lang="scss" scoped>
	.second-rectangle {
		border-radius: 1.56rem;
		backdrop-filter: blur(2.63rem);
		background: var(--bg--color2);
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		width: 80%;
		height: auto;
		margin: 10px 0;
		box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);

		.divider {
			height: 1px;
			width: 90%;
			/* 与文字宽度一致 */
			background-color: white;
			// margin: 10px auto; /* 居中对齐 */
		}

		.hourly-forecast {
			display: flex;
			flex-direction: row;
			justify-content: space-around;
			width: 100%;
			margin: 1.44rem;

			.hour {
				display: flex;
				flex-direction: column;
				align-items: center;

				.time {
					font-size: 16px;
					color: #ffffff;
					margin-bottom: 4px;
				}

				.temp-container {
					display: flex;
					flex-direction: row;
					align-items: center;
					margin-bottom: 8px;

					.weather-icon {
						width: 24px;
						height: 24px;
						color: #ffffff;
					}

					.temp {
						font-size: 16px;
						color: #ffffff;
					}
				}
			}
		}
	}
</style>